package com.larry.sync;

/**
 * @ProjectName JUC
 * @Author larry
 * @Date 14:54 2021/7/9
 * @Description 虚假唤醒
 **/

class Share {
    private int number = 0;
    public synchronized void incr() throws InterruptedException {
//        if (number != 0){
//            this.wait();
//        }
        while (number != 0){
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "---" + number);
        this.notifyAll();
    }
    public synchronized void decr() throws InterruptedException {
//        if (number != 1){
//            this.wait();
//        }
        while (number != 1){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "---" + number);
        this.notifyAll();
    }
}

public class ThreadDemo1 {

    public static void main(String[] args) {
        Share share = new Share();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"AA").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.decr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"BB").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"CC").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    share.decr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"DD").start();
    }

}
